package com.cat.yygh.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cat.yygh.cmn.client.DictFeignClient;
import com.cat.yygh.common.exception.YyghException;
import com.cat.yygh.common.util.JwtHelper;
import com.cat.yygh.enums.AuthStatusEnum;
import com.cat.yygh.model.user.Patient;
import com.cat.yygh.model.user.UserInfo;
import com.cat.yygh.user.mapper.PatientMapper;
import com.cat.yygh.user.mapper.UserInfoMapper;
import com.cat.yygh.user.service.PatientService;
import com.cat.yygh.user.service.UserInfoService;
import com.cat.yygh.vo.user.LoginVo;
import com.cat.yygh.vo.user.UserAuthVo;
import com.cat.yygh.vo.user.UserInfoQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2023-11-15
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper,UserInfo> implements UserInfoService{
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PatientMapper patientMapper;
    @Autowired
    private DictFeignClient dictFeignClient;
    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        //1.先获取用户输入的手机号和验证码信息
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //2.对接受的信息作非空验证
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){
            throw new YyghException(20001,"手机号或验证码有误");
        }
        //3. 对验证码进一步校验
        String redisCode = (String) redisTemplate.opsForValue().get(phone);
        if (!redisCode.equals(code) || StringUtils.isEmpty(redisCode)){
            throw new YyghException(20001,"验证码有误");
        }
        //获取微信openid
        String openid = loginVo.getOpenid();
        Map<String, Object> map  = new HashMap<>();
        if (StringUtils.isEmpty(openid)){
            //无微信的openid 扫码授权成功时候已经将信息存入数据库
            //根据手机查询数据库
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("phone",phone);
            UserInfo userInfo = baseMapper.selectOne(wrapper);
            //如果返回对象为空，就是第一次登录，存到数据库登录数据
            if(userInfo == null) {
                userInfo = new UserInfo();
                userInfo.setName("");
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }
            //判断用户是否可用
            if(userInfo.getStatus() == 0) {
                throw new YyghException(20001,"用户已经禁用");
            }
            map = get(userInfo);
        }else {
            //已经扫码授权成功 数据库有openid
            //1 创建userInfo对象，用于存在最终所有数据
            UserInfo userInfoFinal = new UserInfo();
            //2 根据手机查询数据
            // 如果查询手机号对应数据,封装到userInfoFinal
            UserInfo userInfoPhone =
            baseMapper.selectOne(new QueryWrapper<UserInfo>().eq("phone", phone));
            //数据库有之前手机登录注册的剩余的手机号
            if(userInfoPhone != null) {
                // 如果查询手机号对应数据,封装到userInfoFinal
                BeanUtils.copyProperties(userInfoPhone,userInfoFinal);
                //把手机号数据删除 绑定手机号到openid上
                baseMapper.delete(new QueryWrapper<UserInfo>().eq("phone", phone));
            }
            //3 根据openid查询微信信息
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("openid",openid);
            UserInfo userInfoWX = baseMapper.selectOne(wrapper);
            //4 把微信信息封装userInfoFinal
            userInfoFinal.setId(userInfoWX.getId());
            userInfoFinal.setOpenid(userInfoWX.getOpenid());
            userInfoFinal.setNickName(userInfoWX.getNickName());
            //数据库表没有相同绑定手机号，设置值
            if(userInfoPhone == null) {
                userInfoFinal.setPhone(phone);
                userInfoFinal.setStatus(userInfoWX.getStatus());
            }
            System.out.println(userInfoFinal);
            //修改手机号
            baseMapper.updateById(userInfoFinal);
            //5 判断用户是否锁定
            if(userInfoFinal.getStatus() == 0) {
                throw new YyghException(20001,"用户被锁定");
            }
            //6 登录后，返回登录数据
            map = get(userInfoFinal);
        }
        return map;
    }
    /*根据id获取用户信息*/
    @Override
    public UserInfo getUserInfo(Long userId) {
        UserInfo info = baseMapper.selectById(userId);
        //利用枚举
        info.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(info.getAuthStatus()));
        return info;
    }

    @Override
    public void update(Long userId, UserAuthVo userAuthVo) {
        UserInfo info = new UserInfo();
        info.setId(userId);
        info.setAuthStatus(1);
        BeanUtils.copyProperties(userAuthVo,info);
        baseMapper.updateById(info);
    }

    @Override
    public Page<UserInfo> selectPage(long page, long limit, UserInfoQueryVo queryVo) {
        Page<UserInfo> pageParam = new Page<>(page,limit);
        //组装查询条件
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(queryVo.getKeyword())) {
            wrapper.like("name",queryVo.getKeyword()).or().eq("phone",queryVo.getKeyword());
        }
        if(!StringUtils.isEmpty(queryVo.getStatus())){
            wrapper.eq("status",queryVo.getStatus());
        }
        if(!StringUtils.isEmpty(queryVo.getAuthStatus())) {
            wrapper.eq("auth_status",queryVo.getAuthStatus());
        }
        if(!StringUtils.isEmpty(queryVo.getCreateTimeBegin())) {
            wrapper.gt("create_time",queryVo.getCreateTimeBegin());
        }
        if(!StringUtils.isEmpty(queryVo.getCreateTimeEnd())) {
            wrapper.lt("create_time",queryVo.getCreateTimeEnd());
        }
        //调用mapper的方法
        Page<UserInfo> pages = baseMapper.selectPage(pageParam, wrapper);
        //编号变成对应值封装
        pages.getRecords().stream().forEach(item -> {
            this.packageUserInfo(item);
        });
        return pages;
    }

    @Override
    public void lock(Long userId, Integer status) {
        if(status == 0 || status == 1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }
    }

    @Override
    public Map<String, Object> show(Long id) {
        Map<String,Object> map = new HashMap<>();
        //根据userid查询用户信息
        UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(id));
        map.put("userInfo",userInfo);
        //根据userid查询就诊人信息
        QueryWrapper<Patient> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",id);
        List<Patient> patientList = patientMapper.selectList(wrapper);
        //通过远程调用，得到编码对应具体内容，查询数据字典表内容
        patientList.stream().forEach(item ->{
            //封装其他参数
            this.packPatient(item);
        });
        map.put("patientList",patientList);
        return map;
    }

    @Override
    public void approval(Long userId, Integer authStatus) {
        if(authStatus == 2 || authStatus == 1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }

    //封装Patient其他参数
    private Patient packPatient(Patient item) {
        //获取证件对应名称
        String name = dictFeignClient.getNameByValue(Long.parseLong(item.getCertificatesType()));
        //省
        String province = dictFeignClient.getNameByValue(Long.parseLong(item.getProvinceCode()));
        //市
        String city = dictFeignClient.getNameByValue(Long.parseLong(item.getCityCode()));
        //区
        String district = dictFeignClient.getNameByValue(Long.parseLong(item.getDistrictCode()));

        item.getParam().put("certificatesTypeString",name);
        item.getParam().put("provinceString",province);
        item.getParam().put("cityString",city);
        item.getParam().put("districtString",district);
        item.getParam().put("fullAddress",province+city+district+item.getAddress());
        return item;
    }
    private UserInfo packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus().intValue()==0 ?"锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }

    private Map<String,Object> get(UserInfo userInfo) {
        //返回页面显示名称
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        //根据userid和name生成token字符串
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token",token);
        return map;
    }
}
